package net.ib.mtalk.ui.attachment.vcard;

import java.util.ArrayList;

import net.ib.mtalk.R;
import net.ib.mtalk.ui.attachment.vcard.ContactStruct.EmailData;
import net.ib.mtalk.ui.attachment.vcard.ContactStruct.ImData;
import net.ib.mtalk.ui.attachment.vcard.ContactStruct.NoteData;
import net.ib.mtalk.ui.attachment.vcard.ContactStruct.PhoneData;
import net.ib.mtalk.ui.attachment.vcard.ContactStruct.PostalData;
import net.ib.mtalk.ui.attachment.vcard.account.AccountData;
import net.ib.mtalk.ui.attachment.vcard.account.AccountMgr;
import android.app.Dialog;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AddVCardDialog extends Dialog {

	private static final int KIND_EMAIL = 1;
	private static final int KIND_POSTAL = 2;
//	private static final int KIND_IM = 3;
//	private static final int KIND_ORGANIZATION = 4;
	private static final int KIND_PHONE = 5;
	
	private Context mContext;
	private Dialog dialog;
	
	ListView contactList;
	
	private ArrayList<AccountData> mAccounts;
	private AccountAdapter mAccountAdapter;
	private AccountData mSelectedAccount;
	
	public AddVCardDialog(Context context) {
		super(context);
		mContext = context;
		dialog = this;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.activity_contact_list);

		contactList = (ListView) findViewById(R.id.addContactList);
		
		mAccounts = AccountMgr.getInstance(mContext).getAccountsData(mContext, true);
		
		if(mAccounts.size() <= 0){
			Toast.makeText(mContext, R.string.toast_contacts_not_found, Toast.LENGTH_SHORT).show();
			new Handler().post(new Runnable(){
				public void run() {
					dismiss();
				}});
			return;
		}
		
		mAccountAdapter = new AccountAdapter(mContext, mAccounts);
		contactList.setAdapter(mAccountAdapter);
		
		contactList.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ContactStruct items = VCardReadActivity.getContactInfo();
			
				if(items != null){
					mSelectedAccount = mAccounts.get(position);
					ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
					ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
							.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, mSelectedAccount.getType())
							.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, mSelectedAccount.getName())
							.build());
					ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
							.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
							.withValue(ContactsContract.Data.MIMETYPE, 
									   ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
							.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, items.name)
							.build());
					if(items.fullName != null){
						ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
								.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
								.withValue(ContactsContract.Data.MIMETYPE, 
										   ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
								.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, items.fullName)
								.build());
					}
					if(items.company != null){
						ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
								.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
								.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
								.withValue(ContactsContract.CommonDataKinds.Organization.DATA, items.company)
								.build());
					}
					if(items.noteList != null){
						for(NoteData note : items.noteList){							
							ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
									.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
									.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
									.withValue(ContactsContract.CommonDataKinds.Note.NOTE, note.note)
									.build());
						}
					}
					if(items.phoneList != null){
						for(PhoneData phone : items.phoneList){
							ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
									.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
									.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
									.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone.number)
									.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phone.type)
									.withValue(ContactsContract.CommonDataKinds.Phone.LABEL, phone.label)
									.build());
						}
					}
					if(items.emailList != null){
						for(EmailData email : items.emailList){
							ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
									.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
									.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
									.withValue(ContactsContract.CommonDataKinds.Email.DATA, email.address)
									.withValue(ContactsContract.CommonDataKinds.Email.TYPE, email.type)
									.withValue(ContactsContract.CommonDataKinds.Email.LABEL, email.label)
									.build());
						}
					}
					if(items.postalList != null){
						for(PostalData postal : items.postalList){
							ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
									.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
									.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, postal.formattedAddress)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, postal.street)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POBOX, postal.pobox)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD, postal.neighborhood)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, postal.city)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, postal.region)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, postal.postalCode)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, postal.country)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, postal.type)
									.withValue(ContactsContract.CommonDataKinds.StructuredPostal.LABEL, postal.label)
									.build());
						}
					}
					if(items.imList != null){
						for(ImData im : items.imList){
							ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
									.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
									.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
									.withValue(ContactsContract.CommonDataKinds.Im.DATA, im.data)
									.withValue(ContactsContract.CommonDataKinds.Im.TYPE, im.type)
									.withValue(ContactsContract.CommonDataKinds.Im.LABEL, im.customProtocol)
									.withValue(ContactsContract.CommonDataKinds.Im.PROTOCOL, im.protocol)
									.withValue(ContactsContract.CommonDataKinds.Im.CUSTOM_PROTOCOL, im.customProtocol)
									.build());
						}
					}
					int duration = Toast.LENGTH_SHORT;
					try {
						mContext.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
						CharSequence txt = mContext.getString(R.string.toast_contact_create_success);
						Toast createToast = Toast.makeText(mContext, txt, duration);
						createToast.show();
			        } catch (Exception e) {
			            // Display warning
			            CharSequence txt = mContext.getString(R.string.toast_contact_create_failed);
			            Toast toast = Toast.makeText(mContext, txt, duration);
			            toast.show();
			        }
			        dismiss();
				}else{
					Toast.makeText(mContext, R.string.toast_contact_not_saved, Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
	
	private class AccountAdapter extends ArrayAdapter<AccountData> {
		
		private LayoutInflater mInflater;
		
		public AccountAdapter(Context context, ArrayList<AccountData> accountData) {
            super(context, android.R.layout.simple_spinner_item, accountData);
            mContext = context;
			mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
		
		public View getView(int position, View convertView, ViewGroup parent) {
            // Inflate a view template
            if (convertView == null) {
                convertView = (RelativeLayout)mInflater.inflate(R.layout.item_account_entry, parent, false);
            }
            TextView firstAccountLine = (TextView) convertView.findViewById(R.id.firstAccountLine);
            TextView secondAccountLine = (TextView) convertView.findViewById(R.id.secondAccountLine);
            ImageView accountIcon = (ImageView) convertView.findViewById(R.id.accountIcon);

            // Populate template
            AccountData data = getItem(position);
            firstAccountLine.setText(data.getName());
            secondAccountLine.setText(data.getTypeLabel());
            Drawable icon = data.getIcon();
            if (icon == null) {
                icon = mContext.getResources().getDrawable(android.R.drawable.ic_menu_search);
            }
            accountIcon.setImageDrawable(icon);
            return convertView;
		}
	}
}
